package cn.icatw.gulimall.search.service.impl;

import cn.icatw.common.to.es.SkuEsModel;
import cn.icatw.gulimall.search.config.GulimallElasticSearchConfig;
import cn.icatw.gulimall.search.constant.EsConstant;
import cn.icatw.gulimall.search.service.ProductSaveService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author icatw
 * @date 2022/3/11
 * @email 762188827@qq.com
 * @apiNote
 */
@Service
@Slf4j
public class ProductSaveServiceImpl implements ProductSaveService {
    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        //保存到es中
        //建立索引 product，建立映射关系
        //给es批量保存数据

        BulkRequest bulkrequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            ///构造保存请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            String jsonString = JSON.toJSONString(skuEsModel);
            indexRequest.source(jsonString, XContentType.JSON);
            bulkrequest.add(indexRequest);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkrequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
        //感知错误
        //TODO 如果批量es保存出错 有错为true
        boolean b = bulk.hasFailures();
        List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        log.info("商品上架成功：{}", collect);
        return b;
    }
}
